package org.model.common.injector;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.AbstractWrapper;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ExceptionUtils;

import java.util.List;

/**
 * 自定义mapper.
 *
 * @author zenghao
 * @date 2023/8/13
 */
public interface CommonMapper<T> extends BaseMapper<T> {

    /**
     * 批量保存 insert into table(...) values(...),(...),(...)
     * @param list
     * @return
     */
    int insertBatchSomeColumn(List<T> list);

    @Override
    default T selectOne(Wrapper<T> queryWrapper) {
        // 校验是否包含limit
        boolean hasLimit = StrUtil.containsIgnoreCase(queryWrapper.getSqlSegment(), "limit");
        if (!hasLimit) {
            // 通过wrapper对象添加限制条件
            if (queryWrapper instanceof AbstractWrapper) {
                ((AbstractWrapper<?, ?, ?>) queryWrapper).last("LIMIT 2");
            }
        }
        List<T> ts = this.selectList(queryWrapper);
        if (CollectionUtils.isNotEmpty(ts)) {
            if (ts.size() != 1) {
                throw ExceptionUtils.mpe("One record is expected, but the query result is multiple records");
            }
            return ts.get(0);
        }
        return null;
    }
}
